package main

import (
	"flag"
	"github.com/howeyc/fsnotify"
	"log"
	"os"
	"os/exec"
)

func runBashScript(command string) {
	cmd := exec.Command(command)
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}

// Now, it only what create event.
var (
	WatchPath     = ""
	WatchFileName = ""
)

func main() {

	fDir := flag.String("D", "", "\tThe Dir or File to watch")
	fName := flag.String("F", "filename", "\tThe file to watch")

	execShell := flag.String("X", "", "\tThe Script to exec")

	flag.Parse()

	if *fDir == "" {
		flag.PrintDefaults()
		os.Exit(2)
	}
	WatchPath = *fDir
	WatchFileName = *fName

	dirLen := len(WatchPath)
	if WatchPath[dirLen-1:dirLen] != "/" {
		WatchPath = WatchPath + "/"
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	done := make(chan bool)

	// Process events
	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				if ev.IsCreate() {
					if ev.Name == WatchFileName {
						log.Println("create event:", ev)
						os.Remove(WatchPath + WatchFileName)
						log.Printf(*execShell)
						runBashScript(*execShell)
					}
				}
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch(WatchPath)
	if err != nil {
		log.Fatal(err)
	}

	<-done

	/* ... do stuff ... */
	watcher.Close()
}
